package org.miyuki4j.cfgtool;

import lombok.Getter;
import org.miyuki4j.cfgtool.exception.DataVerifyException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/24/星期四 17:01
 * @Version 1.0
 */
@Getter
public class TableData implements Iterable<TableDataRow>, DataVerifiable {

    private final TableMeta meta;

    private final List<TableDataRow> rows = new ArrayList<>();

    public TableData(TableMeta meta) {
        this.meta = meta;
    }

    public void add(TableDataRow row) {
        rows.add(row);
    }

    @Override
    public Iterator<TableDataRow> iterator() {
        return rows.iterator();
    }

    @Override
    public void verify() {
        try {
            meta.parse();
        } catch (CfgToolException e) {
            throw e;
        } catch (Exception e) {
            throw new DataVerifyException("TableMeta:" + meta, e);
        }
        for (TableDataRow row : rows) {
            for (TableDataCell cell : row) {
                try {
                    Optional<TableField> optionalTableField = meta.getHeader().get(cell.getColumn());
                    if (!optionalTableField.isPresent()) {
                        throw new DataVerifyException("No field found for column " + cell.getColumn());
                    }
                    if (StringUtils.isNotBlank(cell.getValue())) {
                        TableField tableField = optionalTableField.get();
                        String exportValue = tableField.verify(cell.getValue());
                        cell.setExportValue(exportValue);
                        Object instance = optionalTableField.get().instance(exportValue);
                        if (instance == null) {
                            throw new DataVerifyException("Invalid value for column " + cell.getColumn());
                        }
                    }
                } catch (DataVerifyException e) {
                    throw e;
                } catch (Exception e) {
                    throw new DataVerifyException(e);
                }
            }
        }
    }
}
